package views

import (
	"errors"
	"log"
	"net/http"
	"strconv"
	"strings"
	"study/go-blog/common"
	"study/go-blog/service"
)

func (*HTMLApi) Category(response http.ResponseWriter, request *http.Request) {
	categoryTemplate := common.Template.Category
	path := request.URL.Path
	prefix := strings.TrimPrefix(path, "/c/")
	cid, err := strconv.Atoi(prefix)
	if err != nil {
		categoryTemplate.WriteError(response, errors.New("不识别此请求路径"))
		return
	}

	if err := request.ParseForm(); err != nil {
		log.Println("表单获取失败", err)
		categoryTemplate.WriteError(response, errors.New("系统错误，请联系管理员"))
		return
	}

	pageStr := request.Form.Get("page")
	if pageStr == "" {
		pageStr = "1"
	}

	page, _ := strconv.Atoi(pageStr)
	pageSize := 10

	categoryResponse, err := service.GetPostsByCategoryId(cid, page, pageSize)
	if err != nil {
		categoryTemplate.WriteError(response, err)
		return
	}
	categoryTemplate.WriteData(response, categoryResponse)

}
